#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define BUF_SIZE (4096)

void* client_read(void* arg)
{
	int cli_fd = *(int*)arg;
	char buf[BUF_SIZE];
	
	//接受数据
	for(;;)
	{
		int recv_size = read(cli_fd,buf,BUF_SIZE);
		if(0 >= recv_size || 0 == strcmp(buf,"quit"))
		{
			printf("已经与服务器断开链接\n");
			pthread_exit(NULL);
		}
		printf("%s\n",buf);
	}
}

int main()
{
	//创建socket对象
	printf("创建socket对象...\n");
	int cli_fd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > cli_fd)
	{
		perror("socket");
		return -1;
	}
	
	//准备通信地址(服务端)
	printf("准备通信地址...\n");
	struct sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6789);
	addr.sin_addr.s_addr = inet_addr("10.0.2.15");//此处填写自己的ip地址
	socklen_t addrlen = sizeof(addr);
	
	//链接服务端
	printf("链接服务端口...\n");
	if(connect(cli_fd,(struct sockaddr*)&addr,addrlen))
	{
		perror("connect");
		return -1;
	}
	
	char buf[BUF_SIZE];
	
	read(cli_fd,buf,BUF_SIZE);
	if(NULL == strstr(buf,"链接成功"))
	{
		printf("群聊人已满，请稍后再来\n");
		close(cli_fd);
		return 0;
	}
	printf("%s\n",buf);
	
	//链接成功，创建客户端
	pthread_t tid;
	pthread_create(&tid,NULL,client_read,&cli_fd);
	
	//输入昵称
	char name[BUF_SIZE] = {};
	printf("请输入你的昵称：");
	gets(name);
	write(cli_fd,name,strlen(name)+1);
	
	//发送数据
	for(;;)
	{
		printf(">>");
		gets(buf);
		
		char msg[BUF_SIZE];
		sprintf(msg,"%s:%s",name,buf);
		
		int send_size = write(cli_fd,msg,strlen(msg)+1);
		if(0 >= send_size || 0 == strcmp(buf,"quit"))
		{
			printf("结束通信\n");
			close(cli_fd);
			pthread_exit(NULL);
			return 0;
		}
	}
}

